package com.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.common.constant.AuthServerConstant;
import com.common.exception.BizCodeEnume;
import com.common.utils.R;
import com.common.vo.MemberResponseVO;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.feign.TirdPartFeignService;
import com.gulimall.auth.vo.UserLoginVo;
import com.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author mayifan
 * @version 1.0
 * @date 2025-01-02 20:29
 */
@Controller
public class LoginController {

    @Autowired
    TirdPartFeignService tirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(s)){
//            检查是否过了有效期，如果没有过有效期那么就返回error
//            过了有效期的话，就继续下面的流程获取新的验证码
            if(Long.parseLong(s.split("_")[1]) - System.currentTimeMillis() <60000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = String.valueOf((int)((Math.random() + 1) * 100000));
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code+"_"+System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        tirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping(value = "/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        System.out.println(vo.toString());
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
//        校验当前的验证码是否正确
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            if(s.split("_")[0].equals(vo.getCode())){
//                验证码正确，调用远程服务
                R r = memberFeignService.regist(vo);
                if(r.getCode()==0){
//                删除验证码
                    redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getMsg());
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String Login(UserLoginVo vo,HttpSession session,RedirectAttributes redirectAttributes){

        R r = memberFeignService.login(vo);
        if(r.getCode()==0) {
            MemberResponseVO loginUser = r.getData(new TypeReference<MemberResponseVO>() {
            });
            // 成功放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER, loginUser);
            return "redirect:http://gulimall.com";
        }else{
            String msg = r.getMsg();
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",msg);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            //没登录
            return "login";
        } else{
            return "redirect:http://gulimall.com";
        }
    }
}
